/* SPDX-License-Identifier: GPL-2.0-only */
#include <asm/kexec.h>
#include <linux/linkage.h>
#include <asm/segment.h>
#include <asm/page_types.h>
#include <asm/processor-flags.h>
#include <asm/msr-index.h>

#define PARK_MAGIC 0x7061726b

	.text
	.align PAGE_SIZE
	.code64
SYM_CODE_START(park_cpu)
	.code64
	/*
	 * %rdi pgd addr
	 * %rsi __do_cpu_park addr
	 * %rdx park exit addr
	 */

	/* get physical address of page table now too */
	movq	%rdi, %r9
	/* Switch to the identity mapped page tables */
	movq	%r9, %cr3

	movq	%cr4, %rax
	movq	%rax, %r13

	/*
	 * Set cr0 to a known state:
	 *  - Paging enabled
	 *  - Alignment check disabled
	 *  - Write protect disabled
	 *  - No task switch
	 *  - Don't do FP software emulation.
	 *  - Proctected mode enabled
	 */
	movq	%cr0, %rax
	andq	$~(X86_CR0_AM | X86_CR0_WP | X86_CR0_TS | X86_CR0_EM), %rax
	orl		$(X86_CR0_PG | X86_CR0_PE), %eax
	movq	%rax, %cr0

	/*
	 * Set cr4 to a known state:
	 *  - physical address extension enabled
	 *  - 5-level paging, if it was enabled before
	 */
	movl	$X86_CR4_PAE, %eax
	testq	$X86_CR4_LA57, %r13
	jz	1f
	orl	$X86_CR4_LA57, %eax
1:
	movq	%rax, %cr4

	jmp 1f
1:

	mov	%rdx, %rdi
	mov	%rsi, %rax
	addq    $(__do_cpu_park - park_cpu), %rax
	jmp	*%rax

	ret	/* never */
SYM_CODE_END(park_cpu)

SYM_CODE_START(__do_cpu_park)
	.code64

	/* %rdi park exit addr */

	leaq	gdt(%rip), %rax
	/* gdt address will be updated with the same value several times */
	movq	%rax, (gdt_meta + 0x2)(%rip)
	lgdt	gdt_meta(%rip)

	movl	$0x18, %eax	/* data segment */
	movl	%eax, %ds
	movl	%eax, %es
	movl	%eax, %ss
	movl	%eax, %fs
	movl	%eax, %gs

	/* set stack */
	leaq	stack_init(%rip), %rsp
	leaq	__enter_protection(%rip), %rax
	/* stack will be writted with the same value several times */
	pushq	$0x08 /* CS */
	pushq	%rax
	lretq

	.code32
__enter_protection:
	/* Disable paging */
	movl	%cr0, %eax
	andl	$~0x80000000, %eax
	movl	%eax, %cr0

	/* Disable long mode */
	movl	$0xC0000080, %ecx
	rdmsr
	andl	$~0x00000100, %eax
	wrmsr

	/* Disable PAE */
	xorl	%eax, %eax
	movl	%eax, %cr4

	mov	$PARK_MAGIC, %eax
	mov	%eax, 0x8(%edi)
0:
	mov	(%edi), %eax
	test	%eax, %eax
	jz	0b

	mov	$0x18, %edx
	jmp	*%eax

	.balign 16
gdt:
	/* 0x00 unusable segment
	 */
	.quad	0

	/* 0x08 32 4GB flat code segment */
	.word	0xFFFF, 0x0000, 0x9B00, 0x00CF /* protect mode */

	/* 0x10 4GB flat code segment */
	.word	0xFFFF, 0x0000, 0x9B00, 0x00AF /* long mode */

	/* 0x18 4GB flat data segment */
	.word	0xFFFF, 0x0000, 0x9300, 0x00CF

gdt_end:
gdt_meta:
	.word	gdt_end - gdt - 1
	.quad	gdt
	.word	0, 0, 0
stack:	.quad	0, 0
stack_init:
SYM_CODE_END(__do_cpu_park)
	.fill	PAGE_SIZE - (. - park_cpu), 1, 0
	.globl park_cpu_code_size
.set park_cpu_code_size, . - park_cpu
